//
//  HistoryNumView.m
//  夺宝吧
//
//  Created by xiaocai on 15/7/3.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "HistoryNumView.h"
#import "HisNumCell.h"
#import "HisNumHeader.h"
#import "HisNumModel.h"
//查看参与号码
#define HIS_NUM_URL @"/api/ApiGoods/getBoughtCodes"

@interface HistoryNumView ()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    UIView *whiteView;
    //瀑布流
    UICollectionView *_collectionView;
    UILabel *countLab;
    //数据源
    NSMutableArray *_data;
    //记录id
    NSString *_psc_id;
    NSString *_qishu;
    NSString *_owner_id;
   
}

@end
@implementation HistoryNumView
-(instancetype)initWithPdcId:(NSString *)pdcId AndQiShu:(NSString *)qishu AndTitle:(NSString *)title Owner:(NSString *)uid
{
    if (self = [super init]) {
        self.frame = CGRectMake(0, 0, WYMWITH, WYMHEIGHT);
        _psc_id = pdcId;
        _qishu = qishu;
        _owner_id = uid;
        _data = [NSMutableArray array];
        self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        whiteView = [[UIView alloc]initWithFrame:CGRectMake(20, 0, WYMWITH - 40, WYMHEIGHT - 250*app.autoSizeScaleY)];
        whiteView.backgroundColor = [UIColor whiteColor];
        whiteView.center = CGPointMake(WYMWITH/2, WYMHEIGHT/2);
        //分割线
        [whiteView addSubview:[WYPublic getFenGexian:0 :50 :whiteView.frame.size.width :0.5]];
        UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, whiteView.frame.size.width-20, 50)];
        titleLab.numberOfLines = 2;
        
        titleLab.font = [UIFont systemFontOfSize:14];
        titleLab.text = title;
        [whiteView addSubview:titleLab];
        
        countLab = [[UILabel alloc]initWithFrame:CGRectMake(4, CGRectGetMaxY(titleLab.frame)+2, whiteView.frame.size.width - 8, 20)];
        countLab.font = [UIFont systemFontOfSize:14];
        [whiteView addSubview:countLab];
        //瀑布流
        [self loadCollectionView];
        
        //分割线
        [whiteView addSubview:[WYPublic getFenGexian:0 :whiteView.frame.size.height - 50 :whiteView.frame.size.width :0.5]];
        
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        backBtn.frame = CGRectMake(0, 0, 200, 50);
        backBtn.center = CGPointMake(whiteView.frame.size.width/2, whiteView.frame.size.height - 25);
        [backBtn setTitle:@"确定" forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(backBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
        
        [whiteView addSubview:backBtn];
        [self addSubview:whiteView];
    }
    return self;
}
//确定按钮的监听事件
- (void)backBtnOnClick
{
    [self removeFromSuperview];
}
//用瀑布流显示号码
- (void)loadCollectionView
{
    //初始化瀑布流
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(countLab.frame), whiteView.frame.size.width, whiteView.frame.size.height - 102-countLab.frame.size.height) collectionViewLayout:layout];
    //设置代理
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    
    //注册cell
    UINib *nib = [UINib nibWithNibName:@"HisNumCell" bundle:nil];
    [_collectionView registerNib:nib forCellWithReuseIdentifier:@"cell"];
//    [_collectionView registerNib:[UINib nibWithNibName:@"HisNumHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hxwHeader"];
    [_collectionView registerClass:[HisNumHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hxwHeader"];
//    [_collectionView registerClass:[HisNumHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"hxwFooter"];
//    [_collectionView registerNib:[UINib nibWithNibName:@"HisNumHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"hxwFooter"];
    
    [whiteView addSubview:_collectionView];
    
    //请求数据
    [self requestForData];
    
}


- (void)requestForData
{
    [WYPublic addHudToWindow];
    NSDictionary *params = @{@"uid":_owner_id,@"id":_psc_id,@"qishu":_qishu};
//    NSLog(@"---id=%@,qi=%@,uid=%@")
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,HIS_NUM_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        NSNumber *c_n = dic[@"data"][@"go_total"];
        countLab.attributedText = [WYPublic getRedMiddleStrWithLeft:@"参与" Middle:[NSString stringWithFormat:@"%d",[c_n intValue]] RightStr:@"次,夺宝号码" Font:14];
        NSDictionary *nums = dic[@"data"][@"list"];
        NSString *flagStr = dic[@"data"][@"q_user_code"];
        
        if (nums.count > 0) {
            NSArray *keys = [nums allKeys];
            // 利用block进行排序
            keys = [keys sortedArrayUsingComparator:
                    ^NSComparisonResult(NSString *obj1, NSString *obj2) {
                        // 先按照姓排序
                        NSComparisonResult result = [obj1  compare:obj2];
                        return result;
                    }];
            //倒叙
            keys = [[keys reverseObjectEnumerator] allObjects];
            for (NSString *key in keys) {
                HisNumModel *model = [[HisNumModel alloc]init];
                model.sectionTitle = key;
                NSArray *rows = dic[@"data"][@"list"][key];
                for (NSString *row in rows) {
                    HisNumModel *rmodel = [[HisNumModel alloc]init];
                    rmodel.rownum = row;
                    NSLog(@"%@",row);
                   if ([flagStr class] != [NSNull class] && [row isEqualToString:flagStr]) {
                       rmodel.numFlag = YES;
                   }
                   [model.sectionData addObject:rmodel];
                }
                [_data addObject:model];
            }

        }
        [_collectionView reloadData];
        [WYPublic removeHudToWindow];
    } failedBlock:^{
        [WYPublic removeHudToWindow];
    } needLog:NO];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _data.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize size = {WYMWITH,20};
    return size;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    HisNumHeader *headView = nil;
    
    if([kind isEqual:UICollectionElementKindSectionHeader])
    {
        headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hxwHeader" forIndexPath:indexPath];
    }
       if (_data.count > 0) {
        HisNumModel *model = _data[indexPath.section];
        [headView setLabelText:model.sectionTitle];
    }
    return headView;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    return CGSizeMake(whiteView.frame.size.width/3.0, 20*myDelegate.autoSizeScaleY);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    HisNumModel *model = _data[section];
    return model.sectionData.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HisNumCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (_data.count>0) {
        //获取当前数据模型
        HisNumModel *model = _data[indexPath.section];
        HisNumModel *row = model.sectionData[indexPath.row];
        //填充cell
        [cell fillCellWithModel:row];
    }
    //    cell.selectedBackgroundView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    return cell;
}

@end
